from masonite.controllers import Controller
from masonite.views import View
from masonite.response import Response
from masonite.request import Request
from app.traits.MyControllerTrait import MyControllerTrait
from app.traits.MyModelTrait import MyModelTrait
from app.models.AdminRole import AdminRole
from masonite.facades import Session
from app.models.AdminActionLog import AdminActionLog
from app.my_package.MyPackage import MyValidator


class AdminRoleController(Controller):
    uri = "/admin/role"
    temp = "admin.role"

    def index(self, view: View):
        uri = self.uri + '/index'
        data = {
            'uri': self.uri,
            'uri2': "/admin/role-permission",
            'menus': MyControllerTrait.get_menu_nav(uri),
            "title": MyControllerTrait.get_permission_title(uri)
        }
        return view.render(self.temp+".index", data)

    def show(self, request: Request, response: Response):
        title = request.input("title")
        page = request.input("page", 1)
        limit = request.input("limit", 10)
        table = AdminRole.get_table_name()
        where = ''
        order = 'id DESC'

        if len(title) > 0:
            where = "title LIKE '%{0}%'".format(title)

        total, admin_roles = MyModelTrait.search_for_show(table, where, '*', page, limit, order)
        if admin_roles is not None:
            for index, admin_role in enumerate(admin_roles):
                admin_roles[index]['created_at'] = MyControllerTrait.time_format_conversion(admin_role['created_at'])
                admin_roles[index]['updated_at'] = MyControllerTrait.time_format_conversion(admin_role['updated_at'])

        data = {
            'code': 0,
            'message': 'success',
            'total': total,
            'data': admin_roles
        }
        return response.json(data)

    def create(self, view: View):
        data = {
            'uri': self.uri,
        }
        return view.render(self.temp + '.create', data)

    def store(self, request: Request, response: Response):
        title = request.input('title')
        b, m = MyValidator.ch_alpha_num(title)
        if b is False:
            return response.json({'code': 0, 'message': '标题' + m})
        b, m = MyValidator.between(title, 1, 30)
        if b is False:
            return response.json({'code': 0, 'message': '标题' + m})

        admin_role = AdminRole.where('title', title).first()
        if admin_role is not None:
            return response.json({'code': 0, 'message': '角色名称 {0} 已存在'.format(title)})

        AdminRole.generate_log(title)
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}".format(title)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': '成功'})

    def edit(self, request: Request, response: Response, view: View):
        admin_role_id = request.input("id")
        b, m = MyValidator.is_integer(int(admin_role_id))
        if b is False:
            return response.json({'code': 0, 'message': m})

        admin_role = AdminRole.where('id', admin_role_id).first()
        if admin_role is None:
            return response.json({'code': 0, 'message': '未找到角色'})

        data = {
            'uri': self.uri,
            'data': admin_role,
        }
        return view.render(self.temp + ".edit", data)

    def update(self, request: Request, response: Response):
        admin_role_id = request.input("id")
        title = request.input("title")

        b, m = MyValidator.is_integer(int(admin_role_id))
        if b is False:
            return response.json({'code': 0, 'message': 'id' + m})
        b, m = MyValidator.ch_alpha_num(title)
        if b is False:
            return response.json({'code': 0, 'message': '标题' + m})
        b, m = MyValidator.between(title, 1, 30)
        if b is False:
            return response.json({'code': 0, 'message': '标题' + m})

        admin_role = AdminRole.where('id', admin_role_id).first()
        if admin_role is None:
            return response.json({'code': 0, 'message': '未找到角色'})
        if admin_role['title'] != title:
            admin_role.update({'title': title})
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}".format(title)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': '成功'})

    def destroy(self, request: Request, response: Response):
        admin_role_id = request.input("id")
        b, m = MyValidator.is_integer(int(admin_role_id))
        if b is False:
            return response.redirect(location=self.uri + '/index', status=302)

        admin_role = AdminRole.where('id', admin_role_id).first()
        if admin_role is None:
            return response.redirect(location=self.uri + '/index', status=302)
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}".format(admin_role.title)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path, request.ip(), remark)
        admin_role.delete()
        return response.json({'code':1, 'message':'成功'})